package com.test.multithread.classLoader.newInstance;

import com.test.multithread.classLoader.Person;
import org.springframework.util.SerializationUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException, CloneNotSupportedException {
        //1、new关键字
        Person person1 = new Person();
        System.out.println("new关键字" + person1); // Person{name='null', age=null}
        //2. Class.newInstance
        Person person21 = new Person();
        Person person22 = Person.class.newInstance();
        System.out.println("Class.newInstance" + person22); // Person{name='null', age=null}

        //3.Constructor.newInstance
        // 包括public的和非public的，当然也包括private的
        Constructor<?>[] declaredConstructors = Person.class.getDeclaredConstructors();
        // 只返回public的~~~~~~(返回结果是上面的子集)
        Constructor<?>[] constructors = Person.class.getConstructors();

        Constructor<?> noArgsConstructor = declaredConstructors[0];
        Constructor<?> haveArgsConstructor = declaredConstructors[1];

        noArgsConstructor.setAccessible(true); // 非public的构造必须设置true才能用于创建实例
        Object person31 = noArgsConstructor.newInstance();
        Object person32 = declaredConstructors[1].newInstance("fsx", "16");
        System.out.println("Constructor.newInstance" + person31);
        System.out.println("Constructor.newInstance" + person32);


        //4.Clone
        Person person4 = new Person();
        Object clone = person4.clone();

        System.out.println(person4);
        System.out.println("Clone" + clone);
        System.out.println(person4 == clone); //false


        //5.序列化
        Person person5 = new Person();
        byte[] bytes = SerializationUtils.serialize(person5);

        // 字节数组：可以来自网络、可以来自文件（本处直接本地模拟）
        Object deserPerson = SerializationUtils.deserialize(bytes);
        System.out.println("序列化" + person5);
        System.out.println(deserPerson);
        System.out.println(person5 == deserPerson);
/*————————————————
        版权声明：本文为CSDN博主「学海无边苦作舟」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
        原文链接：https://blog.csdn.net/weixin_41255211/article/details/115034453*/
    }
}
